<?php

namespace app\service;

use app\model\MemberWalletModel;
use app\model\MemberWithdrawalModel;
use support\Db;
use support\facade\Logger;
use const support\CORRECT;
use const support\wallet_types_1;

class WithdrawalService
{

    //提现操作
    public static function toWithdrawalOperation(int $memberId,array $data): bool
    {
        //检测可提现金额和提现金额是否可行
        $balance=MemberWalletService::getWithdrawAbleAmount($memberId);
        if ($balance<$data['withdrawal_amount']){
            return false;
        }
        Db::beginTransaction();
        try {
            //添加申请提现信息
            $insert=[
                'member_id'     =>$memberId,
                'withdrawal_sn' =>createOrderTradeNo(),
                'withdrawal_amount'=>$data['withdrawal_amount'],
                'create_time'=>time(),
                'bank_name'=>$data['bank_name']??'',
                'bank_number'=>$data['bank_number']??'',
                'bank_region'=>$data['bank_region']??'',
                'bank_branch'=>$data['bank_branch']??'',
                'real_name'=>$data['real_name']??''
            ];
            $id=MemberWithdrawalModel::insertGetId($insert);
            if (!$id){
                Db::rollBack();
                return false;
            }
            $ret=MemberWalletModel::increment('frozen_amount',$data['withdrawal_amount'],[
                'member_id'     =>$memberId,
                'wallet_type'   =>wallet_types_1,
                'status'        =>CORRECT
            ]);
            if (!$ret){
                Db::rollBack();
                return false;
            }
            Db::commit();
            return true;
        }catch (\Throwable $e){
            Db::rollBack();
            Logger::app($e);
            return false;
        }
    }

    //提现明细
    public static function withdrawalDetails(int $memberId,int $page,int $limit): array
    {
        $model=MemberWithdrawalModel::where([
            'member_id'     =>$memberId
        ]);
        //计算总数量
        $totalNum=$model->count();
        $offset=($page-1)*$limit;
        $lists=MemberWithdrawalModel::where([
            'member_id'     =>$memberId
        ])->select([
            'id','member_id','withdrawal_sn','withdrawal_amount','create_time','status'
        ])->offset($offset)->limit($limit)->get()->append(['status_tip'])->toArray();
        return commonPagingData($lists,$page,$limit,$totalNum);
    }


}